package com.gs.spring.core;

import java.lang.reflect.Field;
import java.util.Date;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import com.gs.spring.core.util.Timestamp;

@Component
public class TimestampingBeanPostProcessor implements BeanPostProcessor {

	@Override
	public Object postProcessAfterInitialization(final Object bean,
			final String beanName) throws BeansException {
		return bean;
	}

	@Override
	public Object postProcessBeforeInitialization(final Object bean, final String beanName)
			throws BeansException {
		ReflectionUtils.doWithFields(bean.getClass(),
				new ReflectionUtils.FieldCallback() {
					public void doWith(Field field)
							throws IllegalArgumentException,
							IllegalAccessException {
						field.set(bean, new Date());
					}
				}, new ReflectionUtils.FieldFilter() {
					public boolean matches(Field field) {
						return field.getType() == Date.class
								&& field.getAnnotation(Timestamp.class) != null;
					}
				});
		return bean;
	}

}
